# -*- coding: utf-8 -*-
# @Time    : 2024/8/9 14:58
# @Author  : Jonny
# @File    : LuckGitlabFileService.py

from luck.gitlab.LuckGitlabApi import LuckGitlabApi
from luck.util.LuckDbMysqlHelperUtils import LuckDbMysqlHelperUtils
from luck.core.LuckConstant import LuckConstant
from luck.gitlab.LuckGitlabUserService import LuckGitlabUserService
import uuid
from datetime import datetime
import json


class LuckGitlabFileService(object):

    def __init__(self, config):
        self.config = config
        
    TABLE_NAME = "luck_gitlab_file"

    # 添加文件
    def add(self, parameters):
        parameters["id"] = str(uuid.uuid4())  # 生成UUID作为主键
        parameters["version"] = 1
        parameters["regt"] = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M:%S")
        # 构建字段名和参数列表
        fields = []
        values = []
        for key, value in parameters.items():
            if value is not None:
                fields.append(key)
                if isinstance(value, dict):
                    # 如果value是dict类型，先将其转换为json字符串
                    values.append(json.dumps(value))
                else:
                    # 对于非dict类型，直接添加value
                    values.append(value)

        # 构建SQL文件
        placeholders = ', '.join(['?'] * len(fields))
        sql_template = f"INSERT INTO {self.TABLE_NAME} ({', '.join(fields)}) VALUES ({placeholders})"
        # 输出文件（使用占位符以避免文件中的SQL注入风险）
        logging_placeholders = ', '.join(['%s'] * len(fields))
        logging_sql = f"添加文件语句：INSERT INTO {self.TABLE_NAME} ({', '.join(fields)}) VALUES ({logging_placeholders})"
        print(logging_sql % tuple(values))

        db_host = self.config["db_host"]
        db_port = self.config["db_port"]
        db_name = self.config["db_name"]
        db_user = self.config["db_user"]
        db_password = self.config["db_password"]
        db_helper = LuckDbMysqlHelperUtils(db_host, db_port, db_name, db_user, db_password)
        with db_helper as um:
            sql_template = sql_template.replace("?", "%s")
            um.cursor.execute(sql_template, values)

        obj = self.read({
            "id": parameters["id"]
        })["data"][0]
        return {
            "code": LuckConstant.CODE_SUCCESS,
            "msg": "操作成功",
            "data": obj
        }

    # 删除文件
    def delete(self, parameters):
        if "id" not in parameters or ("id" in parameters and len(parameters["id"]) <= 0):
            return {
                "code": LuckConstant.CODE_FAIL,
                "msg": "id不能为空"
            }
        id_value = parameters["id"]
        sql = f"delete from {self.TABLE_NAME} where id='{id_value}'"
        print(f"删除文件语句：{sql}")

        db_host = self.config["db_host"]
        db_port = self.config["db_port"]
        db_name = self.config["db_name"]
        db_user = self.config["db_user"]
        db_password = self.config["db_password"]
        db_helper = LuckDbMysqlHelperUtils(db_host, db_port, db_name, db_user, db_password)
        with db_helper as um:
            um.cursor.execute(sql)

    # 修改文件
    def update(self, parameters):
        parameters["modt"] = datetime.strftime(datetime.now(), "%Y-%m-%d %H:%M:%S")
        if "id" not in parameters or ("id" in parameters and len(parameters["id"]) <= 0):
            return {
                "code": LuckConstant.CODE_FAIL,
                "msg": "id不能为空"
            }
        id_value = parameters["id"]
        old_obj = self.read({
            "id": id_value
        })["data"][0]
        parameters["version"] = float(old_obj["version"])+1

        # 遍历parameters字典，并构建SET子句的条件
        conditions = []
        for key, value in parameters.items():
            if value is not None:
                if isinstance(value, dict):
                    value = json.dumps(value)
                conditions.append(f"{key} = '{value}'")
        # 如果存在条件，将它们用英文逗号连接起来，并添加到SQL查询中
        sql_update = ""
        if conditions:
            sql_update = ", ".join(conditions)
        sql = f"update {self.TABLE_NAME} set {sql_update} where id='{id_value}'"
        print(f"修改文件语句：{sql}")

        db_host = self.config["db_host"]
        db_port = self.config["db_port"]
        db_name = self.config["db_name"]
        db_user = self.config["db_user"]
        db_password = self.config["db_password"]
        db_helper = LuckDbMysqlHelperUtils(db_host, db_port, db_name, db_user, db_password)
        with db_helper as um:
            um.cursor.execute(sql)

        obj = self.read({
            "id": id_value
        })["data"][0]
        return {
            "code": LuckConstant.CODE_SUCCESS,
            "msg": "操作成功",
            "data": obj
        }

    # 查询文件
    def read(self, parameters):
        conditions = []
        for key, value in parameters.items():
            if value is not None:
                conditions.append(f"a.{key} = '{value}'")

        sql = f"select a.* from {self.TABLE_NAME} a where 1=1 "
        if conditions:
            sql += " AND " + " AND ".join(conditions)

        sql += " order by a.id asc "
        db_host = self.config["db_host"]
        db_port = self.config["db_port"]
        db_name = self.config["db_name"]
        db_user = self.config["db_user"]
        db_password = self.config["db_password"]
        db_helper = LuckDbMysqlHelperUtils(db_host, db_port, db_name, db_user, db_password)
        with db_helper as um:
            um.cursor.execute(sql)

            # 初始化一个空列表来保存结果
            result_list = []

            # 遍历查询结果
            for row in um.cursor.fetchall():
                if row["regt"] is not None:
                    row["regt"] = datetime.strftime(row["regt"], "%Y-%m-%d %H:%M:%S")
                # 将字典添加到列表中
                result_list.append(row)

            print(f"查询文件条数：{len(result_list)}，数据：{result_list}")
            return {
                "code": LuckConstant.CODE_SUCCESS,
                "msg": "操作成功",
                "data": result_list
            }